package main

import (
	"bytes"
	"compress/gzip"
	"context"
	"fmt"
	"go.manyji.com/lib/encoding/json"
	"go.manyji.com/lib/log"
	"go.manyji.com/lib/util/errors"
	"net/http"
	"sieve_agent_server/lib/server"
	"strings"
)

func HandleExclude(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	ss := strings.Split(r.URL.Path[1:], "/")

	uid := GetLoginUid(r)
	if uid == 0 {
		w.WriteHeader(http.StatusForbidden)
		w.Write([]byte("not login"))
		return
	}

	_ = r.ParseForm()
	ctx := &server.Context{Uid: uid, Args: r.PostForm, Http: &server.ContextHttp{ResponseWriter: w, Request: r}}

	op := ""
	if len(ss) > 1 {
		op = ss[len(ss)-1]
	}
	var data []byte
	var err error
	switch op {
	case "GetBusinessType":
		data, err = json.Marshal(GetBusinessType(ctx))
		break
	case "GetSieveSourceConfig":
		data, err = json.Marshal(GetSieveSourceConfig(ctx))
		break
	case "GetSysDefine":
		{
			respData := make(map[string]interface{})
			respData["ResourceList"] = server.GetModTree(uid)
			if respUser, err := (&data_User{}).GetUserDetail(context.Background(), uint64(uid)); err != nil {
				log.Err(fmt.Sprintf("获取用户信息失败：%+v", err))
			} else {
				respData["UserInfo"] = respUser
			}

			data, err = json.Marshal(respData)
			break
		}
	default:
		{
			err = errors.New("permission denied")
		}
	}
	if err != nil {
		w.WriteHeader(http.StatusForbidden)
		_, _ = w.Write([]byte(err.Error()))
		return
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.Header().Set("Content-Encoding", "gzip")
	buf := new(bytes.Buffer)
	gzw := gzip.NewWriter(buf)
	leng, err := gzw.Write(data)
	if err != nil || leng == 0 {
		return
	}
	err = gzw.Flush()
	if err != nil {
		return
	}
	err = gzw.Close()
	if err != nil {
		return
	}
	bt := buf.Bytes()
	_, _ = w.Write(bt)
}
